import { request } from './useRequest';
const PORT = 3001;

// 上传切片，同时过滤已上传的切片
export async function uploadChunks(chunkData, container) {
    const requestList = chunkData
        .map(({ chunk, hash, index, fileHash }) => {
            // 创建一个FormData存储文件
            const formData = new FormData();

            formData.append('chunk', chunk);
            formData.append('hash', hash);
            formData.append('totalSize', container.file.size);
            formData.append('filename', container.file.name);
            formData.append('fileHash', fileHash);
            return { formData, index };
        })
        .map(async ({ formData, index }) => {
            await request({
                url: `http://localhost:${PORT}`,
                data: formData,
                onProgress: createProgressHandler(chunkData[index])
            });
        });

    await Promise.all(requestList);
}

// 发送请求校验服务端是否存在这个文件
export async function verifyUpload(filename, fileHash) {
    const { data } = await request({
        url: `http://localhost:${PORT}/verify`,
        method: 'post',
        headers: {
            'content-type': 'application/json'
        },
        data: JSON.stringify({
            filename,
            fileHash
        })
    });

    return JSON.parse(data);
}

// 创建进度条handler
export function createProgressHandler(item) {
    return (e) => {
        item.percentage = parseFloat(String(e.loaded / e.total * 100));
    };
}

export function structureChunkData(fileChunkList, container) {
    return fileChunkList.map(({ file }, index) => ({
        chunk: file,
        index,
        percentage: 0,
        hash: container.hash + '-' + index, // 文件名 + 文件所在数组下标
        fileHash: container.hash
    }));
}